<template>
    <view>
        <scroll-view :scroll-y="true" :scroll-x="false" class="scroll" @scrolltolower="bindlower">
            <view class="wuge" v-if="allShops == '' || allShops.length == 0">没有任何实体信息</view>
            <view class="list" v-for="(item, index) in allShops" :key="index">
                <view class="item">
                    <view class="image" @tap="toDetail" :data-id="item.deptId + ',' + item.deptName + ',' + item.trainCount">
                        <image :src="item.shopLogo" />
                    </view>
                    <view class="content">
                        <text class="h1" @tap="toDetail" :data-id="item.deptId + ',' + item.deptName + ',' + item.trainCount">{{ item.deptName }}</text>
                        <text class="p" @tap="toDetail" :data-id="item.deptId + ',' + item.deptName + ',' + item.trainCount">{{ item.introduce }}</text>
                        <text class="p myp" @tap="openLocation" :data-id="item.longitude + ',' + item.latitude + ',' + item.deptName + ',' + item.region + ',' + item.address">
                            {{ item.province }}{{ item.city }}{{ item.region }}{{ item.address }}
                        </text>
                    </view>
                    <view class="number">
                        <view class="sum">{{ item.trainCount }}种课程</view>
                        <!-- <button class="weui-btn" bindtap="appointment" data-id="{{item.deptId+','+item.deptName}}">预约</button> -->
                        <button class="weui-btn" @tap="toMeal" :data-id="item.deptId + ',' + item.deptName + ',' + item.trainCount">下单</button>
                    </view>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script>
var config = require('../../config.js');
var http = require('../../utils/httpHelper.js');
import wx from 'weixin-js-sdk';
export default {
    data() {
        return {
            allShops: [],
            isLogin: false,
            sumPrice: 0,
            timer: {},
            shopPage: {
                current: 1,
                pageSize: 10,
                total: 0
            }
        };
    },
    onLoad: function () {
        let userInfo = uni.getStorageSync('user');
        if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
            this.setData({
                isLogin: true
            });
        }
        this.wxInit();
    },
    methods: {
        wxInit() {
          uni.setStorageSync('WxCodeUrl', location.href);
          let userInfo = uni.getStorageSync('user');
          if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
              this.setData({
                  isLogin: true
              });
          }
          this.onChangeLocation();
        },
        async getMoreData() {
            let dataWz = this.getLocation();;
            if (dataWz) {
                var that = this;
                that.shopPage.current++;
                that.getTrainAllList(dataWz, function (list) {
                    let yList = that.allShops;
                    yList = yList.concat(list);
                    that.setData({
                        allShops: yList
                    });
                });
            }
        },

        getTrainAllList: function (dataWz, callback) {
            var that = this;
            http.httpPost(
                config.clubApi.getTrainAllList,
                {
                    appid: config.APPID,
                    pageNo: that.shopPage.current,
                    pageSize: that.shopPage.pageSize,
                    lng: dataWz.longitude==undefined?0:dataWz.longitude,
                    lat: dataWz.latitude==undefined?0:dataWz.latitude
                },
                function (res) {
                    if (res.code == '200') {
                        var list = res.data.pageData;
                        if (typeof callback == 'function') {
                            callback(list);
                        }
                    }
                }
            );
        },

        toDetail: function (e) {
            var idParam = e.currentTarget.dataset.id;
            var idParamAry = idParam.split(',');
            if (idParamAry[2] > 0) {
                uni.navigateTo({
                    url: '../shop/detail/index?id=' + idParamAry[0] + '&shopName=' + idParamAry[1] + '&sell=2'
                });
            } else {
                uni.showToast({
                    title: '没有课程可以展示',
                    icon: 'success',
                    duration: 1000
                });
            }
        },

        toMeal: function (e) {
            var idParam = e.currentTarget.dataset.id;
            var idParamAry = idParam.split(',');
            if (idParamAry[2] > 0) {
                uni.navigateTo({
                    url: '../shop/detail/index?id=' + idParamAry[0] + '&shopName=' + idParamAry[1] + '&sell=1'
                });
            } else {
                uni.showToast({
                    title: '没有课程可以展示',
                    icon: 'success',
                    duration: 1000
                });
            }
        },

        appointment: function (e) {
            if (this.isLogin && uni.getStorageSync('user')) {
                var idParam = e.currentTarget.dataset.id;
                var idParamAry = idParam.split(',');
                uni.navigateTo({
                    url: '/pages/shop/appointment/index?id=' + idParamAry[0] + '&shopName=' + idParamAry[1]
                });
            } else {
                uni.switchTab({
                    url: '/pages/user/index'
                });
            }
        },

        openLocation: function (e) {
            var idParam = e.currentTarget.dataset.id;
            var idParamAry = idParam.split(',');
            let lat = Number(idParamAry[1]);
            let lng = Number(idParamAry[0]);
            console.log('openLocation lat',lat);
            console.log('openLocation lng',lng);
            if(lat && lng){
                uni.openLocation({
                    latitude: Number(lat),
                    longitude:Number(lng),
                    name: idParamAry[2],
                    address: idParamAry[3] + idParamAry[4],
                    success: function (res) {
                        console.log(res);
                        console.log('success');
                    }
                });
            }else{
                uni.showToast({
                    title: '暂无位置信息无法导航位置哦',
                    icon: 'none',
                    duration: 1000
                });
            }
        },

        async onChangeLocation() {
            const ua = navigator.userAgent.toLowerCase();
            let url = window.location.href
            if (/iphone|ipad|ipod/.test(ua)) {
              url = uni.getStorageSync('WxCodeUrl');
            }
            var that = this;
            var data = {
              url:url,
              appid:config.APPID
            };
            await http.httpGet(config.clubApi.getWXInterface, data, function(res) {
              wx.config({
                appId: config.APPID,
                timestamp: res.data.timestamp,
                nonceStr: res.data.nonceStr,
                signature: res.data.signature,
                jsApiList: ['getLocation'],
              });
              that.waitForWxReady().then(() => {
                let dataWz = that.getLocation();
                if (dataWz) {                
                    that.getTrainAllList(dataWz, function (list) {
                        that.setData({
                            allShops: list
                        });
                    });
                }
              }).catch((err) => {
                console.error('err===>>>', err);
                let reg = /request:fail/;
                if (reg.test(err.errMsg)) {
                    reject('noNetWork');
                } else {
                    reject('requestTimeOut');
                }
              })
            })
        },
        waitForWxReady(index) {
          return new Promise((resolve, reject) => {
            if (typeof wx !== 'undefined') {
              if (wx.ready) {
                resolve();
              } else {
                document.addEventListener('WeixinJSBridgeReady', () => {
                  resolve();
                });
              }
            } else {
              reject(new Error('请在微信环境中打开页面'));
            }
          });
        },
        getLocation(){
          return new Promise((resolve, reject) => {
            wx.getLocation({
              type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
              isHighAccuracy: true,
              highAccuracyExpireTime: 3000,
              success: function (res) {
                console.info(res, 124)
                resolve({
                    latitude: res.latitude,
                    longitude: res.longitude
                });
              },
              cancel: function (res) {
                uni.showModal({
                  title: '用户拒绝授权获取地理位置',
                })
              }
            });
          });
        },
        //处理分页
        bindlower: function (e) {
          if(this.timer != null){
            clearTimeout(this.timer)
          }
          this.timer = setTimeout(()=>{
            this.getMoreData();
          },500)
        }
    }
};
</script>
<style lang="scss">
@import './index.scss';
</style>
